<?php

namespace App\Http\Service;

use App\Models\Comment;
use App\Models\Doubanpost;
use App\Models\Baoliaopost;
use App\Models\Commentvote;
use App\Http\Service\UserService;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\DB;

class CommentService extends BaseService
{
    private $model;
    private $doubanpost;
    private $userService;
    private $baoliaopost;
    private $commentvote;

    // 常量定义
    const COMMENT_TYPE_DOUBAN = 1; // 豆瓣评论
    const COMMENT_TYPE_BAOLIAO = 2; // 爆料评论
    
    const VOTE_TYPE_LIKE = 1; // 点赞
    const VOTE_TYPE_DISLIKE = -1; // 点踩
    const VOTE_TYPE_CANCEL = 2; // 取消投票
    
    const STATUS_ACTIVE = 1; // 激活状态
    const STATUS_INACTIVE = 2; // 非激活状态

    public function __construct(
        Comment $model,
        Commentvote $commentvote,
        Doubanpost $doubanpost,
        UserService $userService,
        Baoliaopost $baoliaopost
    ) {
        parent::__construct();
        $this->model = $model;
        $this->doubanpost = $doubanpost;
        $this->userService = $userService;
        $this->baoliaopost = $baoliaopost;
        $this->commentvote = $commentvote;
    }

    /**
     * 统计帖子评论数量
     */
    public function totalComments($request, $data = [])
    {
        $type = $data['type'];
        $uniqueId = $data['unique_id'];
        $peopleId = $data['people_id'];
        
        $where = [
            'unique_id' => $uniqueId,
            'type' => $type,
        ];
        
        $totalCount = $this->model->where($where)->count();
        
        // 更新对应帖子的评论数
        $this->updatePostCommentCount($type, $uniqueId, $totalCount);
        
        // 统计当前用户的评论数
        $userCount = $this->model->where($where)->where('people_id', $peopleId)->count();
        
        return [
            'total_comments' => $totalCount,
            'total_comments_people' => $userCount,
        ];
    }

    /**
     * 获取评论列表（主评论）
     */
    public function getCommentList($request, $data = [])
    {
        $page = intval($request->input('page', $this->cpage));
        $limit = intval($request->input('limit', $this->climit));
        $offset = ($page - 1) * $limit;
        
        $where = [
            ['status', '=', self::STATUS_ACTIVE],
            ['parent_id', '=', 0],
        ];
        
        $this->addCondition($where, $data, 'type');
        $this->addCondition($where, $data, 'unique_id');
        
        $count = $this->model->where($where)->count();
        
        // 构建查询
        $query = $this->model->where($where);
        
        // 排序逻辑
        if (isset($data['status']) && $data['status'] == 1) {
            $query->orderBy('like_count', 'desc');
        } else {
            $query->orderBy('create_time', 'desc');
        }
        
        $list = $query->offset($offset)
                     ->limit($limit)
                     ->get()
                     ->toArray();
        
        // 处理列表数据
        $list = $this->processCommentList($list, $data);
        
        return $this->buildPaginationResult($page, $limit, $count, $list);
    }

    /**
     * 获取子评论列表
     */
    public function getSubCommentList($page = 1, $limit = 30, $parentId, $data = [])
    {
        $page = intval($page) ?: $this->cpage;
        $limit = intval($limit) ?: $this->climit;
        $offset = ($page - 1) * $limit;
        
        // 使用 Laravel 查询构建器替代原生 SQL
        $countQuery = $this->model->whereRaw("JSON_EXTRACT(crumbs, '$[1]') = ?", [$parentId]);
        $count = $countQuery->count();
        
        // 构建查询
        $query = $this->model->whereRaw("JSON_EXTRACT(crumbs, '$[1]') = ?", [$parentId])
                            ->select([
                                'id', 'unique_id', 'parent_id', 'people_id', 'content', 
                                'update_time', 'commented_people_id', 'images', 'address', 
                                'client_ip', 'is_pubisher', 'like_count', 'dislike_count'
                            ]);
        
        // 排序逻辑
        if (isset($data['status']) && $data['status'] == 1) {
            $query->orderBy('like_count', 'desc');
        } else {
            $query->orderBy('create_time', 'desc');
        }
        
        $list = $query->offset($offset)
                     ->limit($limit)
                     ->get()
                     ->toArray();
        
        $list = array_map('get_object_vars', $list);
        $list = $this->processSubCommentList($list, $data);
        
        return $this->buildPaginationResult($page, $limit, $count, $list);
    }

    /**
     * 添加一级评论
     */
    public function addDate1($request, $data = [])
    {
        $commentData = $this->prepareCommentData($data);
        $commentData['parent_id'] = 0;
        
        $commentId = $this->addComment($data['type'], $data['unique_id'], $data['people_id'], $data['content'], 0, $commentData);
        
        if ($commentId) {
            $comment = $this->getCommentWithUserInfo($commentId);
            $this->userService->addDate($request, $data['people_id']);
            return $this->success($comment);
        }
        
        return $this->error();
    }

    /**
     * 添加二级评论
     */
    public function addDate2($request, $data = [])
    {
        $commentData = $this->prepareCommentData($data);
        
        $commentId = $this->addComment($data['type'], $data['unique_id'], $data['people_id'], $data['content'], $data['parent_id'], $commentData);
        
        if ($commentId) {
            $comment = $this->getCommentWithUserInfo($commentId, true);
            $this->userService->addDate($request, $data['people_id']);
            return $this->success($comment);
        }
        
        return $this->error();
    }

    /**
     * 更新评论点赞/点踩数量
     */
    public function updateLikesDislikes($commentId)
    {
        $votes = $this->commentvote->where('comment_id', $commentId)->get()->toArray();
        
        $likeCount = 0;
        $dislikeCount = 0;
        
        foreach ($votes as $vote) {
            switch ($vote['vote_type']) {
                case self::VOTE_TYPE_LIKE:
                    $likeCount++;
                    break;
                case self::VOTE_TYPE_DISLIKE:
                    $dislikeCount++;
                    break;
            }
        }
        
        $this->model->where('id', $commentId)->update([
            'like_count' => $likeCount,
            'dislike_count' => $dislikeCount,
        ]);
    }

    // ========== 私有方法 ==========

    /**
     * 更新帖子评论数
     */
    private function updatePostCommentCount($type, $uniqueId, $count)
    {
        $model = $this->getPostModel($type);
        if ($model) {
            $model->where('unique_id', $uniqueId)->update(['comment_count' => $count]);
        }
    }

    /**
     * 获取对应的帖子模型
     */
    private function getPostModel($type)
    {
        switch ($type) {
            case self::COMMENT_TYPE_DOUBAN:
                return $this->doubanpost;
            case self::COMMENT_TYPE_BAOLIAO:
                return $this->baoliaopost;
            default:
                return null;
        }
    }

    /**
     * 准备评论数据
     */
    private function prepareCommentData($data)
    {
        $defaults = [
            'like_count' => 0,
            'dislike_count' => 0,
            'report_count' => 0,
            'pending_report_count' => 0,
            'is_reported' => self::STATUS_INACTIVE,
            'client_ip' => get_client_ip(),
            'create_time' => date("Y-m-d H:i:s"),
            'update_time' => date("Y-m-d H:i:s"),
        ];
        
        return array_merge($defaults, $data);
    }

    /**
     * 添加评论核心逻辑
     */
    private function addComment($type, $uniqueId, $peopleId, $content, $parentId, $additionalData = [])
    {
        // 获取帖子信息
        $postInfo = $this->getPostInfo($type, $uniqueId);
        $commentInfo = $parentId ? $this->model->find($parentId) : null;
        
        // 构建插入数据
        $insertData = $this->buildCommentData($postInfo, $commentInfo, $uniqueId, $peopleId, $content, $parentId);
        $insertData = array_merge($insertData, $additionalData);
        
        $commentId = $this->model->insertGetId($insertData);
        
        if ($commentId) {
            $this->incrementPostCommentCount($type, $uniqueId);
        }
        
        return $commentId;
    }

    /**
     * 构建评论数据
     */
    private function buildCommentData($postInfo, $commentInfo, $uniqueId, $peopleId, $content, $parentId)
    {
        $data = [
            'unique_id' => $uniqueId,
            'people_id' => $peopleId,
            'content' => $content,
            'status' => self::STATUS_ACTIVE,
            'create_time' => date("Y-m-d H:i:s"),
        ];
        
        if ($commentInfo) {
            $data['parent_id'] = $commentInfo['id'];
            $data['commented_people_id'] = $commentInfo['people_id'];
            $data['crumbs'] = json_encode($this->getCommentCrumbs($commentInfo['id']));
        } else {
            $data['parent_id'] = 0;
            $data['commented_people_id'] = 0;
            $data['crumbs'] = json_encode([0]);
        }
        
        $data['is_pubisher'] = ($postInfo && $peopleId == ($postInfo['user_id'] ?? 0)) ? 1 : 0;
        
        return $data;
    }

    /**
     * 获取评论面包屑
     */
    private function getCommentCrumbs($parentId, $ids = [])
    {
        $idArr = array_merge((array)$parentId, $ids);
        $comment = $this->model->find($parentId);
        
        if ($comment && $comment['parent_id'] != 0) {
            $idArr = $this->getCommentCrumbs($comment['parent_id'], $idArr);
        } else {
            array_unshift($idArr, 0);
        }
        
        return $idArr;
    }

    /**
     * 增加帖子评论数
     */
    private function incrementPostCommentCount($type, $uniqueId)
    {
        $model = $this->getPostModel($type);
        if ($model) {
            $model->where('unique_id', $uniqueId)->increment('comment_count');
        }
    }

    /**
     * 获取帖子信息
     */
    private function getPostInfo($type, $uniqueId)
    {
        $model = $this->getPostModel($type);
        return $model ? $model->where('unique_id', $uniqueId)->first() : null;
    }

    /**
     * 获取带用户信息的评论
     */
    private function getCommentWithUserInfo($commentId, $isSubComment = false)
    {
        $comment = $this->model->find($commentId);
        if (!$comment) return null;
        
        $comment = $comment->toArray();
        $comment['images'] = json_decode($comment['images'], true);
        
        // 添加用户信息
        $userData = $this->userService->update_user($comment['people_id']);
        $comment['people_nickname'] = $userData['nickname'] ?? '';
        $comment['people_avatar'] = $userData['avatar'] ?? '';
        
        // 如果是子评论，添加回复信息
        if ($isSubComment && $comment['commented_people_id']) {
            $replyInfo = $this->getReplyMessage($comment['people_id'], $comment['commented_people_id']);
            $comment = array_merge($comment, $replyInfo);
        }
        
        return $comment;
    }

    /**
     * 获取回复消息
     */
    private function getReplyMessage($peopleId, $commentedPeopleId)
    {
        $userData = $this->userService->getUserData();
        $result = [];
        
        if (isset($userData[$commentedPeopleId]) && isset($userData[$peopleId])) {
            $commentedUser = $userData[$commentedPeopleId];
            $currentUser = $userData[$peopleId];
            
            $commentedNickname = $commentedUser['nickname'];
            $currentNickname = $currentUser['nickname'];
            
            $result = [
                'people_nickname' => $currentNickname,
                'people_avatar' => $currentUser['avatar'],
                'people_msg' => "{$currentNickname}回复{$commentedNickname}",
                '_people_msg' => $commentedNickname,
            ];
        }
        
        return $result;
    }

    /**
     * 处理评论列表
     */
    private function processCommentList($list, $data)
    {
        $userData = $this->userService->getUserData();
        $voteData = $this->getVoteStatusData();
        $userId = $data['user_id'] ?? 0;
        
        foreach ($list as &$item) {
            // 添加用户信息
            if (isset($userData[$item['people_id']])) {
                $user = $userData[$item['people_id']];
                $item['people_nickname'] = $user['nickname'];
                $item['people_avatar'] = $user['avatar'];
            }
            
            $item['images'] = json_decode($item['images'], true);
            $item['son_num'] = $this->model->where('parent_id', $item['id'])->count();
            
            // 添加投票状态
            $voteStatus = $this->getVoteStatus($voteData, $item['id'], $userId);
            $item['like_status'] = $voteStatus['like_status'];
            $item['dislike_status'] = $voteStatus['dislike_status'];
        }
        
        return $list;
    }

    /**
     * 处理子评论列表
     */
    private function processSubCommentList($list, $data)
    {
        $voteData = $this->getVoteStatusData();
        $userId = $data['user_id'] ?? 0;
        
        foreach ($list as &$item) {
            $item['images'] = json_decode($item['images'], true);
            
            // 添加回复信息
            $replyInfo = $this->getReplyMessage($item['people_id'], $item['commented_people_id']);
            if ($replyInfo) {
                $item = array_merge($item, $replyInfo);
            }
            
            // 添加投票状态
            $voteStatus = $this->getVoteStatus($voteData, $item['id'], $userId);
            $item['like_status'] = $voteStatus['like_status'];
            $item['dislike_status'] = $voteStatus['dislike_status'];
        }
        
        return $list;
    }

    /**
     * 获取投票状态数据
     */
    private function getVoteStatusData()
    {
        $votes = $this->commentvote->select(['comment_id', 'user_id', 'vote_type'])->get()->toArray();
        $result = [];
        
        foreach ($votes as $vote) {
            $key = "{$vote['user_id']}_{$vote['comment_id']}";
            $result[$key] = $vote;
        }
        
        return $result;
    }

    /**
     * 获取投票状态
     */
    private function getVoteStatus($voteData, $commentId, $userId)
    {
        $key = "{$userId}_{$commentId}";
        $vote = $voteData[$key] ?? [];
        
        $defaultStatus = ['like_status' => '2', 'dislike_status' => '2'];
        
        if (empty($vote)) {
            return $defaultStatus;
        }
        
        switch ($vote['vote_type']) {
            case self::VOTE_TYPE_LIKE:
                return ['like_status' => '1', 'dislike_status' => '2'];
            case self::VOTE_TYPE_DISLIKE:
                return ['like_status' => '2', 'dislike_status' => '1'];
            case self::VOTE_TYPE_CANCEL:
                return $defaultStatus;
            default:
                return $defaultStatus;
        }
    }

    /**
     * 构建分页结果
     */
    private function buildPaginationResult($page, $limit, $count, $data)
    {
        return [
            'page' => $page,
            'limit' => $limit,
            'count' => $count,
            'total_page' => ceil($count / $limit),
            'data' => $data,
        ];
    }

    /**
     * 添加查询条件
     */
    private function addCondition(&$where, $data, $field)
    {
        if (isset($data[$field]) && !empty($data[$field])) {
            $where[] = [$field, '=', $data[$field]];
        }
    }
}
